﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using IBM.Data.DB2;

using DataSync.Model;
using DataSync.DAL;
using System.Data;
using System.Configuration;

namespace DataSync.BLL
{
    public class Sync
    {
        #region 同步数据
        /// <summary>
        /// 同步数据
        /// </summary>
        /// <param name="instance">同步对象实例</param>
        /// <param name="rows">返回实际同步的记录数</param>
        /// <param name="max">最大ID或最大日期</param>
        /// <returns>正常完成返回TRUE,异常返回FALSE</returns>
        public bool SyncData(SyncBase tableObj, string selectText, out long rows, out object max, SQLHelper sHelper, SQLHelper tHelper, string syncTargetSql)
        {
            rows = 0;
            max = 0;
            long count = 0;
            object maxObj = null;
            string sourceCountText = "";
            System.Data.SqlClient.SqlDataReader reader = sHelper.ExecuteSqlReader(selectText);
            try
            {
                tableObj.BulkCopy.WriteToServer(reader);
            }
            catch (Exception ex)
            {
				
                throw ex;
            }
            finally
            {
                reader.Close();
                reader.Dispose();
            }

            //tableObj.BulkCopy.WriteToServer(dtSource);
            string replaceText = selectText.Trim().Substring(7, selectText.Trim().ToUpper().IndexOf("FROM") - 1 - 7);
            sourceCountText = selectText.Replace(replaceText, " COUNT(1) ");
            rows = long.Parse(tHelper.ExecuteScalar(syncTargetSql).ToString());
            count = long.Parse(sHelper.ExecuteScalar(sourceCountText).ToString());
            string getMaxSql = "";

            if (tableObj.SyncType == 1)
            {
                getMaxSql = "SELECT MAX(" + tableObj.TargetDateFieldName + ") FROM " + tableObj.TargetTableName + "";
            }
            else if (tableObj.SyncType == 2)
            {
                getMaxSql = "SELECT MAX(" + tableObj.TargetIdFieldName + ") FROM " + tableObj.TargetTableName + "";
            }

            if (tableObj.SyncType != 0)
            {
                maxObj = tHelper.ExecuteScalar(getMaxSql);
            }

            //reader.Close();

            max = maxObj;

            return count == rows;
        }
        #endregion

        #region TRUNCATE TABLE
        /// <summary>
        /// 清空已同步数据
        /// </summary>
        /// <param name="tableName">数据表名</param>
        /// <param name="sqlHelper"></param>
        public void ClearTable(string tableName, SQLHelper tqlHelper)
        {
            string deleteText = "TRUNCATE TABLE " + tableName;

            tqlHelper.ExecuteSql(deleteText);
        }
        #endregion

        #region 是否同步并且没有处理同步过后的错误数据
        /// <summary>
        /// 是否同步并且没有处理同步过后的错误数据
        /// </summary>
        /// <param name="checkIsSyncSql">查询_RESULT表中未处理的错误数据数量</param>
        /// <returns></returns>
        public bool IsSync(string checkIsSyncSql, SQLHelper sHelper)
        {
            object objResult = sHelper.ExecuteScalar(checkIsSyncSql);
            return objResult == DBNull.Value || objResult == null ? false : Convert.ToInt32(objResult) > 0;
        }
        #endregion

        #region 验证LOG表是否所有的表全部同步成功
        public bool IsAllSuccess()
        {
            string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["sConnString"].ConnectionString;
            string tConnString = System.Configuration.ConfigurationManager.ConnectionStrings["tConnString"].ConnectionString;
            int allDayTblCount = Convert.ToInt32(ConfigurationManager.AppSettings["TableCount"]);
            int monthSyncDay = int.Parse(ConfigurationManager.AppSettings["MonthSyncDay"]);
            int allMonthTblCount = Convert.ToInt32(ConfigurationManager.AppSettings["MonthTableCount"]);
            SQLHelper sHelper = new SQLHelper(sConnString);
            SQLHelper tHelper = new SQLHelper(tConnString);

            try
            {
                DateTime currentTime = Convert.ToDateTime(sHelper.ExecuteScalar("SELECT GETDATE();"));
                string cmdText = "SELECT COUNT(1) FROM (SELECT TABLE_NAME FROM SYNCHRONIZATION_LOGS WHERE FINISHED=1 AND MAX_TIME>='" + currentTime.AddDays(-1).ToShortDateString() + "' GROUP BY TABLE_NAME) AS A";
                object obj = tHelper.ExecuteScalar(cmdText);
                int tableCount = obj == DBNull.Value || obj == null ? 0 : Convert.ToInt32(obj);
                if (currentTime.AddDays(-1).Day == monthSyncDay)
                {
                    return tableCount >= allDayTblCount + allMonthTblCount;
                }
                else
                {
                    return tableCount >= allDayTblCount;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sHelper.Dispose();
                tHelper.Dispose();
            }
        }
        #endregion

        #region 是否同步完成根据FINISH表判断
        /// <summary>
        /// 是否同步完成根据FINISH表判断
        /// </summary>
        /// <returns></returns>
        public bool IsSyncFinish()
        {
            string tConnString = System.Configuration.ConfigurationManager.ConnectionStrings["tConnString"].ConnectionString;
            SQLHelper tHelper = new SQLHelper(tConnString);

            try
            {
                DateTime currentTime = Convert.ToDateTime(tHelper.ExecuteScalar("SELECT GETDATE();"));
                string cmdText = "SELECT COUNT(1) FROM FINISH_TIME WHERE DATE='" + currentTime.AddDays(-1).ToShortDateString() + "'";
                object obj = tHelper.ExecuteSql(cmdText);
                return obj == DBNull.Value || obj == null ? false : Convert.ToInt32(obj) > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                tHelper.Dispose();
            }
        }
        #endregion
    }
}
